package com.ai.tool.service.impl

import com.ai.tool.entity.Sign
import com.ai.tool.mapper.SignMapper
import com.ai.tool.service.SignService
import com.alibaba.fastjson2.JSONObject
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate
import java.net.URLEncoder
import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

@Service
class SignServiceImpl : ServiceImpl<SignMapper, Sign>(), SignService {


    @Autowired
    lateinit var restTemplate: RestTemplate

    @Autowired
    lateinit var signMapper: SignMapper

    override fun getAddress(): String {
        val id = Random().nextInt(1, 13)
        val sign = signMapper.selectById(id)
        val address = sign.address
        val latitude = sign.latitude
        val longitude = sign.longitude
        val encodedText: String = URLEncoder.encode(address, "UTF-8")
        return "regAddr=$encodedText&lat=$latitude&lng=$longitude&isContinue=1"
    }

    override fun sign(account: String, password: String): JSONObject {
        val jsonObject = JSONObject()
        val currentDate = Date()
        val calendar = Calendar.getInstance()
        calendar.time = currentDate
        val year = calendar.get(Calendar.YEAR)
        val month = (calendar.get(Calendar.MONTH) + 1).toString().padStart(2, '0')
        val day = calendar.get(Calendar.DAY_OF_MONTH).toString().padStart(2, '0')
        val url = "http://tool.bitefu.net/jiari?d=$year$month$day&info=1"
        val headers = HttpHeaders()
        headers.accept = listOf(MediaType.APPLICATION_JSON)
        val requestEntity = HttpEntity<String>(headers)
        val responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject::class.java)
        val type = responseEntity.body?.get("type")
        val typename = responseEntity.body?.get("typename")
        if (type == 0 && typename == "工作日") {
            val loginUrl = "https://hr.richtechcn.com:3210/open_cloud/mobileV16/mobLogin"
            val data = "account=$account&password=$password"
            val loginHeaders = HttpHeaders()
            loginHeaders.contentType = MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8")
            loginHeaders["Host"] = "hr.richtechcn.com:3210"
            loginHeaders["Origin"] = "https://hr.richtechcn.com:3210"
            loginHeaders["Referer"] = "https://hr.richtechcn.com:3210/open_cloud/mobile/v17/dist/index.html"
            loginHeaders["User-Agent"] =
                "Mozilla/5.0 (Linux; Android 13; MI 11 Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.210 Mobile Safari/537.36 MMWEBID/6070 MicroMessenger/8.0.10.2260(0x28000A33) Process/tools NetType/5G Language/zh_CN"
            loginHeaders["X-Requested-With"] = "XMLHttpRequest"
            val loginEntity = HttpEntity(data, loginHeaders)
            val loginResponseEntity =
                restTemplate.exchange(loginUrl, HttpMethod.POST, loginEntity, JSONObject::class.java)
            val loginResponseBody = loginResponseEntity.body
            val status = loginResponseBody?.get("status")
            val message = loginResponseBody?.get("message")
            if (status != -1) {
                val token = loginResponseBody?.get("token_id") as String
                var sessionValue = ""
                val setCookieHeaders = loginResponseEntity.headers["Set-Cookie"]
                if (setCookieHeaders != null) {
                    for (cookieHeader in setCookieHeaders) {
                        val parts = cookieHeader.split(";")
                        for (part in parts) {
                            if (part.trim().startsWith("SESSION=")) {
                                sessionValue = part.trim().substring("SESSION=".length)
                                break
                            }
                        }
                        if (sessionValue.isNotEmpty()) {
                            break
                        }
                    }
                    val checkinUrl = "https://hr.richtechcn.com:3210/open_cloud/mobileLeave/saveRegister"
                    val checkinData = getAddress()
//                        "regAddr=%E5%A4%A9%E6%B4%A5%E5%B8%82%E6%BB%A8%E6%B5%B7%E6%96%B0%E5%8C%BA%E7%AC%AC%E4%B8%89%E5%A4%A7%E8%A1%9751%E5%8F%B7&lat=39.036122&lng=117.71642&isContinue=1"
                    val checkinHeaders = HttpHeaders()
                    checkinHeaders["Host"] = "hr.richtechcn.com:3210"
                    checkinHeaders["Connection"] = "keep-alive"
                    checkinHeaders["Content-Length"] = checkinData.length.toString()
                    checkinHeaders["X-Requested-With"] = "XMLHttpRequest"
                    checkinHeaders["token_id"] = token
                    checkinHeaders["Accept"] = "*/*"
                    checkinHeaders["User-Agent"] =
                        "Mozilla/5.0 (Linux; Android 13; MI 11 Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/90.0.4430.210 Mobile Safari/537.36 MMWEBID/6070 MicroMessenger/8.0.10.2260(0x28000A33) Process/tools NetType/5G Language/zh_CN"
                    checkinHeaders.contentType =
                        MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8")
                    checkinHeaders["Origin"] = "https://hr.richtechcn.com:3210"
                    checkinHeaders["Sec-Fetch-Site"] = "same-origin"
                    checkinHeaders["Sec-Fetch-Mode"] = "cors"
                    checkinHeaders["Sec-Fetch-Dest"] = "empty"
                    checkinHeaders["Referer"] = "https://hr.richtechcn.com:3210/open_cloud/mobile/v17/dist/index.html"
                    checkinHeaders["Accept-Encoding"] = "gzip, deflate"
                    checkinHeaders["Accept-Language"] = "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
                    checkinHeaders["Cookie"] = "SESSION=$sessionValue; app_token_id=$token;"
                    val checkinEntity = HttpEntity(checkinData, checkinHeaders)
                    val checkinResponseEntity =
                        restTemplate.exchange(checkinUrl, HttpMethod.POST, checkinEntity, JSONObject::class.java)
                    val checkinResponseBody = checkinResponseEntity.body
                    if (checkinResponseBody != null) {
                        sendEmail("打卡提醒", checkinResponseBody.toString())
                        jsonObject["msg"] = "打卡成功"
                        jsonObject["result"] = checkinResponseBody
                    }
                }
            } else {
                jsonObject["msg"] = message
            }
        } else {
            jsonObject["msg"] = "今天是法定节假日，不需要打卡"
        }
        return jsonObject
    }

    override fun sendEmail(subject: String, messageText: String) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.host"] = "smtp.qq.com"
        props["mail.smtp.port"] = "587"
        val session = Session.getInstance(props, object : Authenticator() {
            override fun getPasswordAuthentication(): PasswordAuthentication {
                return PasswordAuthentication("1666907097@qq.com", "xfktabwafshycfeh")
            }
        })
        runCatching {
            val message = MimeMessage(session)
            message.setFrom(InternetAddress("1666907097@qq.com"))
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("3118695866@qq.com"))
            message.subject = subject
            message.setText(messageText)
            Transport.send(message)
        }
    }
}


